import { defineComponent, Ref, ref } from 'vue';
import request from '@/request'
import dayjs from "dayjs"
import { SEX, ACCOUNT_STATUS, DEL_FLAG } from '@/dictionaries'
import { Role } from '@/views/controlRole/indexT'

export type User = {
  avatar?: string,
  uName?: string,
  password?: string,
  sex?: number,
  phone?: number,
  email?: string,
  qq?: number,
  wx?: string,
  sign?: string,
  birthday?: string,
  remark?: string,
  delFlag?: string,
  createTime?: string,
  status?: string,
  updateTime?: string,
  uId?: number,
  roles?: Array<Role>,
}

export default defineComponent({
  name: 'controlUser',
  setup() {
    const searchUserName = ref('')     //搜索框用户名
    const searchPhoneNumber = ref('')   //搜索框电话
    const searchStateValue = ref('')     // 搜索框状态
    const options = ref([
      {
        value: '所有',
        label: '所有',
      },
      {
        value: '正常',
        label: '正常',
      },
      {
        value: '停用',
        label: '停用',
      },
    ])
    const bjDisabled = ref(true)  //按钮能否使用 编辑
    const scDisabled = ref(true)  //按钮能否使用 删除
    const selection = ref([])     //复选框返回数组
    const tableData = ref([])   //列表数组
    // 选中内容才可使用编辑，删除
    const handleSelectionChange = (val) => {
      if (val.length == 0) {
        bjDisabled.value = true
        scDisabled.value = true
      } else if (val.length == 1) {
        bjDisabled.value = false
        scDisabled.value = false
      } else {
        bjDisabled.value = true
        scDisabled.value = false
      }
      selection.value = val;
    }
    const dialogImageUrl = ref('') //查看大图 图片路径
    const dialogVisible = ref(false)  //  查看大图
    const dialogFormVisible = ref(false)  //是否显示添加页面弹出框
    const disabled = ref(false)  //
    const avatar = ref('')  //头像上传路径
    const uName = ref('')    //添加用户名
    const password = ref('') //添加密码
    const sex = ref(0)       //性别
    const phone = ref('') //添加手机号
    const email = ref('') //添加邮箱
    const qq = ref('') //添加QQ号
    const wx = ref('') //添加微信号
    const sign = ref('') //用户签名
    const birthday = ref('')   //添加生日
    const remark = ref('') //添加备注信息
    const showUploadImg = ref(true)  //添加图片框，是否显示
    const showFile = ref(false) //已经添加的图片 是否显示阅览图
    const imgList = ref([])   //上传图片数组
    const imgUrlDiv = ref('')  //
    const addOrUpdate = ref(0) //弹出框状态
    // 表格加载状态
    const tableLoading = ref(false)
    //表格title （添加用户 / 修改用户)
    const dialogTitle = ref('添加用户')
    //  添加用户弹出框
    const handleShowAdd = () => {
      dialogTitle.value = '添加用户'
      addOrUpdate.value = 1
      handleClearValue()
      dialogFormVisible.value = true
    }
    //点击提交按钮
    const subAddOrUpdate = () => {
      if (addOrUpdate.value == 1) {
        fnUserInsert()
      } else {
        headleCommitUpdate()
      }
    }
    //清空 所有值
    const handleClearValue = () => {
      uName.value = ''
      password.value = ''
      sex.value = 0
      phone.value = ''
      email.value = ''
      qq.value = ''
      sign.value = ''
      wx.value = ''
      birthday.value = ''
      roles.value = []
      avatar.value = ''
      remark.value = ''
      showUploadImg.value = true
      showFile.value = false
    }
    //查看大图
    const handleShowBigImg = () => {
      dialogImageUrl.value = avatar.value
      dialogVisible.value = true
    }
    //删除图片
    const handleRemoveImg = () => {
      imgList.value = []
      avatar.value = ''
      showUploadImg.value = true
      showFile.value = false
    }
    //用户列表
    const fnUserList = (uName, phone) => {
      tableLoading.value = true
      const params = {
        uName: uName,
        phone: phone,
      }
      request('/api/user/list', 'POST', params).then(
        (res) => {
          tableData.value = res.data
          tableLoading.value = false
        },
      )
    }
    //时间格式转换
    const timeForMat = (row, column, cellValue) => {
      if(cellValue){
        const date = dayjs(cellValue)
        if(dayjs.isDayjs(date)){
          return date.format('YYYY-MM-DD');
        }
      }
      return '--'
    }
    //添加用户
    const fnUserInsert = () => {
      const params:User = {
        avatar: avatar.value,
        uName: uName.value,
        password: password.value,
        sex: sex.value,
        phone: phone.value ? parseInt(phone.value) : 0,
        email: email.value,
        qq: qq.value ? parseInt(qq.value) : 0,
        wx: wx.value,
        sign: sign.value,
        birthday: birthday.value,
        remark: remark.value,
        roles: roles.value || [],
      }
      request('/api/user/insert', 'PUT', params).then((res) => {
          dialogFormVisible.value = false
          fnUserList(null, null)
        },
      )
    }
    //上传图片格式转换成局域网路径
    const fnFileUpload = () => {
      return new Promise((resolve, reject) => {
        const formatDate = new FormData();
        formatDate.append('file', imgList.value[0].raw)
        request('/api/file/upload', 'POST', formatDate, 'multipart/form-data').then(
          (res) => {
            avatar.value = res.data
            resolve(res.data)
          },
        ).catch(
          () => {
            reject('')
          },
        )
      })
    }
    //编辑图片做更改时 ,将内容赋值给 avatar
    const onChange = (file, fileList) => {
      imgList.value = fileList
      if (fileList.length > 0) {
        fnFileUpload()
      }
      showUploadImg.value = false
      showFile.value = true
    }
    const OneColUid = ref('');
    //点击编辑按钮，展示弹出层
    const handleShowUpdate = () => {
      dialogTitle.value = '编辑用户'
      addOrUpdate.value = 2
      selection.value.forEach((v:User) => {
        avatar.value = v.avatar
        if (v.uId) {
          OneColUid.value = v.uId.toString()
        }
        uName.value = v.uName
        password.value = v.password
        sex.value = v.sex
        if (v.phone) {
          phone.value = v.phone.toString()
        }
        email.value = v.email
        if (v.qq) {
          qq.value = v.qq.toString()
        }
        wx.value = v.wx
        sign.value = v.sign
        birthday.value = v.birthday
        remark.value = v.remark
        roles.value = v.roles
      })
      //是否打开编辑框时，展示当行图片
      showFile.value = true
      showUploadImg.value = false
      dialogFormVisible.value = true
    }
    //点击提交编辑
    const headleCommitUpdate = () => {
      if (imgList.value.length > 0) {
        fnFileUpload().then(() => {fnUserUpdate(avatar.value)})
      } else if (imgList.value.length == 0) {
        fnUserUpdate(null)
      }
    }
    //编辑用户
    const roles:Ref<Array<Role>> = ref([]);  //角色信息，还未加入到接口参数中
    const fnUserUpdate = (newAvatar) => {
      const params = {
        avatar: newAvatar,
        uName: uName.value,
        password: password.value,
        sex: sex.value,
        phone: phone.value,
        email: email.value,
        qq: qq.value,
        wx: wx.value,
        sign: sign.value,
        birthday: birthday.value,
        remark: remark.value,
        uId: OneColUid.value,
        roles: roles.value,
      }
      request('/api/user/update', 'POST', params).then(
        (res) => {
          dialogFormVisible.value = false
          fnUserList(null, null)
        },
      )
    }
    //获取所有角色列表
    const roleOptions = ref([]);  //角色列表
    const fnGetRoleList = () => {
      request('/api/role/list', 'POST', {}).then(
        (res) => {
          roleOptions.value = res.data
        },
      )
    }
    const deleteUid = ref([]) //多选 uId 数组
    //删除用户
    const fnUserDelete = () => {
      // selection.value.map(x => {
      //   deleteUid.value.push(x.uId)
      // })
      selection.value.forEach((v) => {
        deleteUid.value.push(v.uId)
      })
      // selection.value = []
      request('/api/user/delete', 'DELETE', { userIds: deleteUid.value }).then(
        (res) => {
          fnUserList(null, null)
          deleteUid.value = []
        })
    }
    //重置搜索框数据
    const headleSearchReset = () => {
      searchUserName.value = ''
      searchPhoneNumber.value = ''
      searchStateValue.value = ''
    }
    return {
      tableLoading,
      searchUserName,
      searchPhoneNumber,
      searchStateValue,
      options,
      tableData,
      addOrUpdate,
      handleSelectionChange,
      bjDisabled,
      scDisabled,
      handleShowAdd,
      dialogFormVisible,
      dialogImageUrl,
      avatar,
      dialogVisible,
      disabled,
      handleShowBigImg,
      uName,
      password,
      sex,
      phone,
      email,
      qq,
      wx,
      sign,
      birthday,
      handleClearValue,
      showUploadImg,
      handleRemoveImg,
      showFile,
      imgList,
      onChange,
      imgUrlDiv,
      fnUserList,
      timeForMat,
      fnUserInsert,
      fnUserDelete,
      fnUserUpdate,
      OneColUid,
      handleShowUpdate,
      headleSearchReset,
      remark,
      roleOptions,
      fnGetRoleList,
      fnFileUpload,
      roles,
      headleCommitUpdate,
      subAddOrUpdate,
      dialogTitle,
      SEX,
      ACCOUNT_STATUS,
      DEL_FLAG,
    }
  },
  components: {},
  created() {
    this.fnUserList(null, null)
    this.fnGetRoleList()
  },
})
